import express from "express";
import { Server } from "socket.io";
import { createServer } from "http";

const app = express();
const server = createServer(app);
const io = new Server(server);

// 使用对象存储在线用户（用户名作为键）
const onlineUsers = {};

io.on("connection", (socket) => {
  console.log("新用户连接");

  // 处理用户名设置
  socket.on("set_username", (username) => {
    if (onlineUsers[username]) {
      socket.emit("username_exists", username);
    } else {
      onlineUsers[username] = socket.id;
      socket.username = username;

      // 通知用户登录成功
      socket.emit("login_success", {
        users: Object.keys(onlineUsers),
        username,
      });

      // 广播用户加入事件
      io.emit("user_joined", username);
    }
  });

  // 处理聊天消息
  socket.on("new_message", (message) => {
    io.emit("message", {
      from: socket.username,
      content: message,
      timestamp: new Date().toISOString(),
    });
  });

  // 处理断开连接
  socket.on("disconnect", () => {
    if (socket.username) {
      delete onlineUsers[socket.username];
      io.emit("user_left", socket.username);
    }
  });
});

// 静态文件服务
app.use(express.static("public"));

const PORT = 3000;
server.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});
